package com.wanmait.recycle.service.impl;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.recycle.dao.SolrDAO;
import com.wanmait.recycle.mapper.QuestionMapper;
import com.wanmait.recycle.pojo.Answer;
import com.wanmait.recycle.pojo.CollectQuestion;
import com.wanmait.recycle.pojo.Question;
import com.wanmait.recycle.pojo.Userinfo;
import com.wanmait.recycle.redis.dao.RedisCollectQuestionDao;
import com.wanmait.recycle.redis.dao.RedisPraiseAnswerDao;
import com.wanmait.recycle.redis.dao.RedisViewCountDao;
import com.wanmait.recycle.redis.pojo.CollectQuestionMessage;
import com.wanmait.recycle.service.CollectQuestionService;
import com.wanmait.recycle.service.ConfigService;
import com.wanmait.recycle.service.QuestionService;
import com.wanmait.recycle.util.PageContext;
import com.wanmait.recycle.util.Pager;

@Service
public class QuestionServiceImpl implements QuestionService {

	@Resource
	private QuestionMapper questionMapper;
	@Resource
	private SolrDAO solrDAO;
	@Resource
	private RedisViewCountDao redisViewCountDao;
	@Resource
	private RedisPraiseAnswerDao redisPraiseAnswerDao;
	@Resource
	private CollectQuestionService collectQuestionService;
	@Resource
	private RedisCollectQuestionDao redisCollectQuestionDao;
	@Resource
	private ConfigService configService;
	
	@Override
	public void insert(Question object) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Question object) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(String ids) {
		// TODO Auto-generated method stub

	}

	@Override
	public Question findById2(Integer questionId) {
		//System.out.println(questionId);
		Question question = questionMapper.findById(questionId);
	
		
		return question;
	}
	
	@Override
	public Question findById(Integer questionId) {
		//System.out.println(questionId);
		Question question = questionMapper.findById(questionId);
		question.setCollectCount(redisCollectQuestionDao.getCount(questionId));
		List<Answer> answers = question.getAnswers();
		
		for (Answer answer : answers) {
			
			answer.setPraiseCount(redisPraiseAnswerDao.getCount(answer.getId()));
		}
		
		return question;
	}

	@Override
	public List<Question> findAll() {
		// TODO Auto-generated method stub
		return questionMapper.findAll();
	}

	@Override
	@Cacheable(value="recycle",key="'question'",condition="#pageNum==1")
	public PageInfo<Question> findAllByPage() {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByPage();
		for (Question question : questions) {
			//从redis中获得收藏数，放入对象中
			question.setCollectCount(redisCollectQuestionDao.getCount(question.getId()));
			//从redis中获得浏览数
			question.setViewCount(redisViewCountDao.getQuestionViewCount(question.getId()));
		}
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}
	
	@Override
	public int getDataCount() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<Question> findAll(Pager pager) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Question> findAll(Question object) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getDataCount(Question object) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<Question> findAll(Pager pager, Question object) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void shangXian(Integer id) {
		questionMapper.shangXian(id);
		
	}

	@Override
	public void xiaXian(Integer id) {
		questionMapper.xiaXian(id);
		
	}

	@Override
	public void shangXianByIds(String ids) {
		
		ids = ids.substring(0, ids.length()-1);
		String[] nn =ids.split(",");
		
		questionMapper.shangXianByIds(nn);
		
	}

	@Override
	public void xiaXianByIds(String ids) {
		
		ids = ids.substring(0, ids.length()-1);
		String[] nn =ids.split(",");
		
		questionMapper.xiaXianByIds(nn);
		
	}

	@Override
	public PageInfo<Question> findAllByRubbishId(Integer rubbishId) {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByRubbishId(rubbishId);
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}

	@Override
	public List<Question> findByRubbishId(Integer rubbishId) {
		// TODO Auto-generated method stub
		List<Question> questions = questionMapper.findAllByRubbishId(rubbishId);
		return questions;
	}

	@Override
	public void addQuestion(Question question) {
		// TODO Auto-generated method stub
		questionMapper.addQuestion(question);
		
	}

	@Override
	public PageInfo<Question> findAllByUserId(Integer id) {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByUserId(id);
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}

	@Override
	public PageInfo<Question> findAllByRubbishIdAndUserinfoId(Integer rubbishId, Integer userinfoId) {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByRubbishIdAndUserinfoId(rubbishId,userinfoId);
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}
	


	@Override
	public List<Question> seachBySolr(String keyword, Pager pager) {
		pager.setPageSize(5);
		return solrDAO.findQuestionPage(keyword, pager);
	}
	
	/*同步队列*/
	@Override
	public void processCollectQueue() {
		// TODO Auto-generated method stub
		//收藏
				List<CollectQuestion> insertCollectQuestionList = new ArrayList<>();
				//取消收藏
				List<CollectQuestion> deleteCollectQuestionList = new ArrayList<>();
				
				while(true)
				{
					
					//获取消息，每次二十条
					List<String> messages = this.popCollectMessage();
					
					for (String message : messages) {
						
						//ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构，反之亦然
						ObjectMapper objectMapper = new ObjectMapper();
						//将redis中的json格式的消息转换为PraiseArticleMessage对象
						CollectQuestionMessage collectQuestionMessage;
						
						try {
							
							collectQuestionMessage = objectMapper.readValue(message, CollectQuestionMessage.class);
							//将解析后的各个属性的值赋给PraiseArtice
							CollectQuestion collectQuestion = new CollectQuestion();
							//存文章id
							Question question= new Question();
							question.setId(collectQuestionMessage.getQuestionId());
							collectQuestion.setQuestion(question);
							//存用户id
							Userinfo userinfo = new Userinfo();
							userinfo.setId(collectQuestionMessage.getUserinfoId());
							collectQuestion.setUserinfo(userinfo);
							//存加入时间
							collectQuestion.setInputTime(new Timestamp(collectQuestionMessage.getInputTime()));
							//如果isDelete为true，加入收藏。如果为false则加入取消
							if(collectQuestionMessage.isDelete()) {
								
								insertCollectQuestionList.add(collectQuestion);
								
							}else {
								
								deleteCollectQuestionList.add(collectQuestion);
							}
							
						} catch (JsonParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JsonMappingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					
					if(insertCollectQuestionList.size()!=0) {
						//批量收藏
						collectQuestionService.insertBatch(insertCollectQuestionList);
					}
					if(deleteCollectQuestionList.size()!=0) {
						//批量取消收藏
						collectQuestionService.deleteBatch(deleteCollectQuestionList);
					}
					
					//小于20条说明队列中没有消息了
					if(messages.size()<20)
					{
						break;
					}
				}
				
			}
	
	/*每次从redis中取出20条消息，如果小于20条，则取完*/
	private List<String> popCollectMessage() {
		List<String> messages = new ArrayList<>();
		for (int i = 0; i < 20 ; i++) {
			
			String message = redisCollectQuestionDao.rightPop();
			if(message!=null) {
				messages.add(message);
			}else {
				break;
			}
		}
		return messages;
	}
	
	/*同步收藏数*/
	@Override
	public void processCollectCount() {
		// TODO Auto-generated method stub
		List<Question> questionList = new ArrayList<>();
		Set<Integer> questionIds = redisCollectQuestionDao.getUpdate();
		Question question = null;
		for (Integer questionId : questionIds) {
			question = new Question();
			Integer collectCount = redisCollectQuestionDao.getCount(questionId);
			question.setId(questionId);
			question.setCollectCount(collectCount);
			
			questionList.add(question);
		}
		for (Question question1 : questionList) {
			
			questionMapper.processCollectCount(question1);
		}
	}

	@Override
	public boolean isCollect(Integer questionId, Integer userinfoId) {
		// TODO Auto-generated method stub
		return redisCollectQuestionDao.isCollect(questionId, userinfoId);
	}

	/*添加收藏*/
	@Override
	public void addCollect(Integer questionId, Integer userinfoId) {
		//System.out.println(":qId"+questionId+",uId:"+userinfoId);
		// TODO Auto-generated method stub
		String message;
		//添加收藏
		redisCollectQuestionDao.addCollectQuestion(questionId, userinfoId);
		//总的收藏数量加1
		redisCollectQuestionDao.increaseCount(questionId);
		
		message="{\"questionId\":"+questionId+",\"userinfoId\":"+userinfoId+",\"delete\":1,\"inputTime\":"+System.currentTimeMillis()+"}";
		
		//想队列中添加消息
		redisCollectQuestionDao.leftPush(message);
		//有哪些问题被操作过
		redisCollectQuestionDao.addUpdate(questionId);
	}

	/*取消收藏*/
	@Override
	public void removeCollect(Integer questionId, Integer userinfoId) {
		// TODO Auto-generated method stub
		String message;
		//添加收藏
		redisCollectQuestionDao.removeCollectQuestion(questionId, userinfoId);
		//总的收藏数量减1
		redisCollectQuestionDao.decreaseCount(questionId);;
		
		message="{\"questionId\":"+questionId+",\"userinfoId\":"+userinfoId+",\"delete\":0,\"inputTime\":"+System.currentTimeMillis()+"}";
		
		//想队列中添加消息
		redisCollectQuestionDao.leftPush(message);
		//有哪些问题被操作过
		redisCollectQuestionDao.addUpdate(questionId);
	}
	
	@Override
	public PageInfo<Question> findAllByPageAndTime() {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByPageAndTime();
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}

	@Override
	public PageInfo<Question> findAllByPageAndRedu() {
		Map<String, Map<String,String>> config = configService.findAllConfig();
		PageHelper.startPage(PageContext.getPageNum(), Integer.parseInt(config.get("前台分页").get("webPage")));
		List<Question> questions = questionMapper.findAllByPageAndRedu();
		PageInfo<Question> pageInfo = new PageInfo<Question>(questions,7);
		return pageInfo;
	}

	/*某个问题被浏览*/
	@Override
	public void addViewQuestion(Integer questionId, String ip) {
		/*添加浏览*/
		redisViewCountDao.addQuestionView(questionId, ip);
		/*增加一次浏览次数*/
		redisViewCountDao.increaseQuestionViewCount(questionId);
		/*哪些文章被浏览*/
		redisViewCountDao.addUpdateViewQuestion(questionId);
	}

	/*判断某篇文章是否被某用户浏览过&&浏览时间是否超过24小时*/
	/*此处返回为是否可以添加浏览，true为可以，false为不可以*/
	@Override
	public boolean isViewQuestion(Integer questionId, String ip) {
		
		return redisViewCountDao.isViewQuestion(questionId, ip);
	}

	/*同步某文章的浏览次数*/
	@Override
	public void processQuestionViewCount() {
		List<Question> questionList = new ArrayList<>();
		Set<Integer> questionIds = redisViewCountDao.getUpdateViewQuestion();
		Question question = null;
		for (Integer questionId : questionIds) {
			question = new Question();
			Integer viewCount = redisViewCountDao.getQuestionViewCount(questionId);
			question.setId(questionId);
			question.setViewCount(viewCount);;
			
			questionList.add(question);
		}
		for (Question question1 : questionList) {
			
			questionMapper.processQuestionViewCount(question1);
		}
		//redisViewCountDao.removeUpdateViewArticle();
		
	}
	
	/*获得某个用户收藏的所有文章*/
	@Override
	public PageInfo<Question> findCollectQuestion(Integer userinfoId) {
			PageHelper.startPage(PageContext.getPageNum(), 10);
			Set<Integer> questionIds = redisCollectQuestionDao.getCollectQuestionIds(userinfoId);
			List<Question> questions = null;
			if(questionIds.size()!=0) {
				questions = questionMapper.findCollectQuestion(questionIds);
				PageInfo<Question> pageInfo = new PageInfo<>(questions,5);
				return pageInfo;
			
		}
		return null;
	}

}
